﻿using Microsoft.AspNetCore.Components.Forms;
using SheepStorage.Domain.Dto.InputDto;
using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Yitter.IdGenerator;

namespace SheepStorage.Service.DataImp
{
    public class SheepWeaningService:ISheepWeaningService
    {
        private readonly IBaseRepository<SheepMomWeaning> _weaningRepository;
        private readonly IBaseRepository<SheepRecord> _recordRepository;
        private readonly IBaseRepository<BuildingManagement> _mentRepository;
        private readonly IBaseRepository<SheepField> _fieldRepository;
        private readonly IBaseRepository<SheepChangeDormitory> _changeRepository;
        private readonly IBaseRepository<SheepMomHistory> _histRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="weaningRepository"></param>
        public SheepWeaningService(IBaseRepository<SheepMomWeaning> weaningRepository,IBaseRepository<SheepRecord> recordRepository,IBaseRepository<BuildingManagement> mentRepository,IBaseRepository<SheepField> fieldRepository,IBaseRepository<SheepChangeDormitory> changeRepository,IBaseRepository<SheepMomHistory> histRepository)
        {
            _weaningRepository = weaningRepository;
            _recordRepository = recordRepository;
            _mentRepository = mentRepository;   
            _fieldRepository = fieldRepository;
            _changeRepository = changeRepository;
            _histRepository = histRepository;
        }



        /// <summary>
        /// 种母断奶添加
        /// </summary>
        /// <param name="sheepWean"></param>
        /// <returns></returns>
        public async Task<int> SheepWeaningAdd(List<SheepMomWeaning> WeanList)
        {
            using (var tran=new TransactionScope())
            {
                try
                {
                    foreach(var sheepWean in WeanList)
                    {
                        var OverbitString = _recordRepository.GetAll().FirstOrDefault(c => c.SheepRecordId == Convert.ToInt32(sheepWean.Overbit)).OverBit;

                        var histList = _histRepository.GetAll().FirstOrDefault(c => c.OverBit == OverbitString && c.MomHistoryWeaningDate == null);

                        if (histList != null)
                        {
                            histList.MomHistoryWeaningDate = sheepWean.WeaningDate;
                            histList.MomHistoryWeaningCount = sheepWean.WeanlingNumber;
                            histList.MomHistoryWeaningWeight = sheepWean.WeaningWeight;
                        }


                        var recordIdList = _recordRepository.GetAll().FirstOrDefault(c => c.SheepRecordId == Convert.ToInt32(sheepWean.Overbit));
                        recordIdList.SheepRecordBreedState = 6;

                        var mentList = _mentRepository.GetAll().FirstOrDefault(c => c.BuildingManagementId == sheepWean.TransferToDormitory);
                        recordIdList.BuildingName = mentList.BuildingName;

                        var fieldList = _fieldRepository.GetAll().FirstOrDefault(c => c.SheepFieldId == sheepWean.DriveField);

                        recordIdList.SheepFieldName = fieldList.SheepFieldName;

                        _recordRepository.Update(recordIdList);


                        var sheepWeaning = new SheepMomWeaning()
                        {
                            Overbit = OverbitString,
                            ElectronicOverbit = OverbitString,
                            WeaningDate = sheepWean.WeaningDate,
                            BreastfeedingDays = sheepWean.BreastfeedingDays,
                            TransferOutDormitory = sheepWean.TransferOutDormitory,
                            RollOutField = sheepWean.RollOutField,
                            TransferToDormitory = sheepWean.TransferToDormitory,
                            DriveField = sheepWean.DriveField,
                            WeanlingNumber = sheepWean.WeanlingNumber,
                            WeaningWeight = sheepWean.WeaningWeight,
                            SheepMomWeight = sheepWean.SheepMomWeight,
                            Remarks = sheepWean.Remarks,
                            Principal = sheepWean.Principal,
                            IsDel = 0,
                            Spermat = 0,
                            DocumentNumber = YitIdHelper.NextId().ToString(),
                            PurchaseSerialNumber = YitIdHelper.NextId().ToString(),
                            AddTime = DateTime.Now
                        };
                        _weaningRepository.Add(sheepWeaning);


                        var changeInfo = new SheepChangeDormitory()
                        {
                            OverBit = OverbitString,
                            ElEarTag = OverbitString,
                            ChangedormitoryType = 5,
                            ChangedormitoryDate = DateTime.Now,
                            TransferOutDormitory = sheepWean.TransferOutDormitory,
                            RollOutField = sheepWean.RollOutField,
                            TransferToDormitory = sheepWean.TransferToDormitory,
                            DriveField = sheepWean.DriveField,
                            Variety = 2,
                            SheepSex = false,
                            Remarks = sheepWean.Remarks,
                            ChangeState = 0,
                            IsDel = 0,
                        };

                        _changeRepository.Add(changeInfo);
                    }

                    tran.Complete();

                    return 1;
                }
                catch (Exception)
                {

                    throw;
                }
            }


                


        }



        /// <summary>
        /// 种母断奶列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<SheepMomWeaning>> GetSheepWeaning(SheepWeaningInput input)
        {
            var list = _weaningRepository.GetAll().Where(c => c.IsDel == 0).ToList();

            if (!string.IsNullOrEmpty(input.WeanStartDate))
            {
                list = list.Where(c => c.WeaningDate >= DateTime.Parse(input.WeanStartDate)).ToList();
            }

            if (!string.IsNullOrEmpty(input.WeanEndDate))
            {
                list = list.Where(c => c.WeaningDate < DateTime.Parse(input.WeanEndDate).AddDays(1)).ToList();
            }

            if (!string.IsNullOrEmpty(input.OverBit))
            {
                list = list.Where(c => c.Overbit == input.OverBit).ToList();
            }

            if (input.TransferTo != null)
            {
                list = list.Where(c => c.TransferToDormitory == input.TransferTo).ToList();
            }

            if (input.Principal != null)
            {
                list = list.Where(c => c.Principal == input.Principal).ToList();
            }

            list = list.OrderByDescending(c => c.SheepMomWeaningId).ToList();

            return list;
        }



        /// <summary>
        /// 批量删除/逻辑删除
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<int> DeleteSheepWeaning(params int[] idList)
        {
            if (idList.Length == 0)
            {
                return 0;
            }

            using (var tran=new TransactionScope())
            {
                try
                {

                    var weanList = _weaningRepository.GetAll().Where(c => idList.Contains(c.SheepMomWeaningId)).ToList();

                    foreach (var item in weanList)
                    {
                        item.IsDel = 1;
                        item.DelTime = DateTime.Now;
                        item.UpdateTime = DateTime.Now;

                    }
                    
                     _weaningRepository.UpdateRange(weanList);

                    //获取耳号
                    var overbits = weanList.Select(w => w.Overbit).ToList();
                    //根据耳号获取数据
                    var recordList = _recordRepository.GetAll().Where(c => overbits.Contains(c.OverBit)).ToList();

                    foreach(var record in recordList)
                    {
                        record.SheepRecordBreedState = 8;
                    }

                    _recordRepository.UpdateRange(recordList);

                    tran.Complete();
                    return weanList.Count;

                }
                catch (Exception)
                {

                    throw;
                }
            }


        }


        /// <summary>
        /// 种母断奶单个数据
        /// </summary>
        /// <param name="sheepWeaningId"></param>
        /// <returns></returns>
        public async Task<SheepMomWeaning> SheepWeaningInfo(int sheepWeaningId)
        {
            var list = _weaningRepository.GetInfoBy(sheepWeaningId);

            return list;
        }


        /// <summary>
        /// 种母断奶修改
        /// </summary>
        /// <param name="sheepWeaning"></param>
        /// <returns></returns>
        public async Task<int> UpdateSheepWeaning(SheepMomWeaning sheepWeaning)
        {
            sheepWeaning.UpdateTime = DateTime.Now;
            sheepWeaning.PurchaseSerialNumber = YitIdHelper.NextId().ToString();
            sheepWeaning.DocumentNumber = YitIdHelper.NextId().ToString();
            sheepWeaning.IsDel = 0;
            sheepWeaning.ElectronicOverbit = sheepWeaning.Overbit;
            var result=_weaningRepository.Update(sheepWeaning);
            return result;
        }


        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="SheepWeaning"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public async Task<int> UpdateSheepWeaningState(SheepWeaningStateInput input)
        {
            var result = _weaningRepository.GetAll().FirstOrDefault(c => c.SheepMomWeaningId == input.SheepMomWeaningId);

            result.Spermat = input.Spermat;

            return _weaningRepository.Update(result);
        }



    }
}
